#!/usr/bin/env python
#-*- coding:utf8 -*-
import web
import time
from app.controllers.application_controller import ApplicationController
from app.helpers.sites_helper import Helper
from app.models.site import Site
from app.models.level import Level
from app.models.site_node import SiteNode
from app.models.site_traffic import SiteTraffic
from app.models.traffic import Traffic
class SitesController(ApplicationController):
    Site        = Site()
    Level       = Level()
    SiteNode    = SiteNode()
    SiteTraffic = SiteTraffic()
    Traffic     = Traffic()

    def initialize(self):
        super(SitesController,self).initialize()
        self.require_login()
        self.data['active'] = self.params.get('controller')

    #网站列表
    def index(self):
        sites = self.Site.get_many_by("uid ='%s' and fid = 0" % self.mid)
        self.data['sites'] = sites

    #验证域名,并获取域名ip
    def _new_frist(self, post):
        host = Helper.get_host(post['domain'])
        return self.render_json({'status':True, 'domain': post['domain'], 'host': host})

    #验证保存网站基本信息
    def _new_second(self, post):
        _host = post['host'].split(':')
        if len(_host) < 2:
            return self.render_json({'msg':'端口或IP不能为空'})
        post['host'] = _host[0]
        post['port'] = _host[1]

        s2,m2 = Helper.is_ipv4(post['host'])
        if s2 is False:
            return self.render_json({'msg':m2})

        if Helper.validation(r".([0-9]){1,4}$", post['port']) is False:
            return self.render_json({'msg':'端口格式不正确.'})
        post['uid'] = self.mid
        if self.Site.create(post):
            return self.render_json({'status': True })
        else:
            return self.render_json({'msg':'添加失败.'})

    #新添加网站
    def new(self):
        self.data['domain'] = None
        self.data['host'] = None
        self.data['levels'] = self.Level.get_many_by("(uid='%s' or type=2) and status =1" % self.mid)
        if self.method == 'POST':
            post = Helper.post()
            s1,m1 = Helper.is_domain(post['domain'])
            if s1 is False:
                return self.render_json({'msg':m1})
            if self.Site.count_by("domain = '%s'" % post['domain']):
                return self.render_json({'msg':'该域名已经存在.'})
            if post['_type'] == '1':
                return self._new_frist(post)
            elif post['_type'] == '2':
                return self._new_second(post)
            return self.render_json({'msg':'操作错误.'})
        else:
            get = Helper.post().get('s')
            if get is None:
                pass
            else:
                post = get.split('|')
                if len(post) == 2:
                    self.data['domain'] = post[0]
                    self.data['host']   = post[1]
                else:
                    pass

    #检测并获取当前网站信息
    def _load_site(self,id):
        site = self.Site.get(id)
        if site is None:
            raise web.notfound()
        self.site       = site
        self.data['site']= site
        self.data['tab']= self.params.get('action')

    #获取当前网站域名CNAME
    def _load_cname(self):
        if self.site.is_cname == 0:
            raise web.seeother('/site/%s/help' % self.site.id)

    #查看当前流量状态
    def show(self,id):
        self._load_site(id)
        self._load_cname()

    #管理当前网站配置信息
    def edit(self,id):
        self._load_site(id)
        self._load_cname()
        subs = self.Site.get_many_by("fid= '%s' and uid = '%s'" % (id,self.mid))
        self.data['nodes']  = self.SiteNode.get_many_by("sid = '%s'" % id)
        self.data['subs']   = subs

    #更新后端IP
    def _update_host(self,post,id):
        s2,m2 = Helper.is_ipv4(post['host'])
        if s2 is False:
            return self.render_json({'msg':m2})
        if self.Site.update_by_host(id,post['host']):
            return self.render_json({'status':True, 'host': post['host']})
        return self.render_json({'msg':'更新失败.'})

    #添加其他域名
    def _update_domain_new(self,post,id):
        #验证域名是否存在
        site = self.Site.get_by("id = '%s' and uid ='%s'" % (id,self.mid))
        if site is None:
            return self.render_json({'msg':'你没有该网站.'})
        s1,m1 = Helper.is_domain(post['domain'])
        if s1 is False:
            return self.render_json({'msg':m1})
        if self.Site.count_by("domain ='%s'" % post['domain']):
            return self.render_json({'msg':'该域名已经存在.'})
        data ={'uid':self.mid,'fid':id,'level':site.level,'domain': post['domain']}
        if self.Site.create_by_sub(id,data):
            return self.render_json({'status': True})
        return self.render_json({'msg': '域名添加失败.'})

    #验证域名信息
    def _load_sub_domain(self,post):
        return self.Site.get_by("id = '%s' and (uid = '%s' and fid !=0 )" % (post['sid'],self.mid))

    #获取编辑域名信息
    def _update_domain_edit(self,post,id):
        site = self._load_sub_domain(post)
        if site is None:
            return self.render_json({'msg': '该域名不存在.'})
        return self.render_json({'status':True,'id':site.id,'domain':site.domain})

    #更新保存域名
    def _update_domain_save(self,post,id):
        site = self._load_sub_domain(post)
        if site is None:
            return self.render_json({'msg': '该域名不存在.'})
        s1,m1 = Helper.is_domain(post['domain'])
        if s1 is False:
            return self.render_json({'msg':m1})
        if self.Site.update_by_domain(id,post['sid'],post['domain']):
            return self.render_json({'status': True})
        return self.render_json({'msg': '域名更新失败.'})

    #删除域名
    def _update_domain_delete(self,post,id):
        site = self._load_sub_domain(post)
        if site is None:
            return self.render_json({'msg': '该域名不存在.'})
        if self.Site.destory_by_sub(id,post['sid']):
            return self.render_json({'status': True})
        return self.render_json({'msg': '域名删除失败.'})

    #修改端口
    def _update_port(self, post, id):
        if Helper.validation(r".([0-9]){1,4}$", post['port']) is False:
            return self.render_json({'msg':'端口格式不正确.'})
        if self.Site.update_by_port(id,post['port']):
            return self.render_json({'status':True, 'port': post['port']})
        return self.render_json({'msg': '端口更新失败.'})

    #更新配置信息
    def update(self,id):
        self._load_site(id)
        self._load_cname()
        if self.method !='POST':
            raise web.notfound()
        post = Helper.post()
        if post['_type'] == 'host':
            return self._update_host(post,id)
        elif post['_type'] == 'domain':
            if post['_ac'] == 'new':
                return self._update_domain_new(post,id)
            elif post['_ac'] == 'edit':
                return self._update_domain_edit(post,id)
            elif post['_ac'] == 'save':
                return self._update_domain_save(post,id)
            elif post['_ac'] == 'delete':
                return self._update_domain_delete(post,id)
        elif post['_type'] == 'port':
            return self._update_port(post,id)
        return self.render_json({'msg':'操作错误.'})

    #网站流量使用情况
    def traffic(self,id):
        self._load_site(id)
        self._load_cname()
        #今天
        end = time.strftime("%Y-%m-%d 00:00:00",time.localtime())
        #判断是否存在流量数据
        if self.SiteTraffic.count_by("(sid = %s and created_at > '%s') and status = 1" % (id, end)):
            #获取流量统计数据
            traffics = self.SiteTraffic.get_many_by("(sid = %s and created_at > '%s') and status = 1" % (id, end), 24 , 'id asc')
            self.data['traffics'] = traffics
            #是否为POST请求
            if self.method == 'POST':
                data = {'hit_byte':[],'total_byte':[],'status':True}
                for traffic in traffics:
                    data['hit_byte'].append(traffic.hit_byte)
                    data['total_byte'].append(traffic.total_byte)
                return self.render_json(data)
        else:
            self.data['traffics'] = None
        #是否为POST请求
        if self.method == 'POST':
            return self.render_json({'msg':'没有该网站的统计数据.'})

    #节点使用情况
    def node(self,id):
        self._load_site(id)
        self._load_cname()

    #CDN 网站规则配置
    def cache(self,id):
        self._load_site(id)
        self._load_cname()
        if self.method == 'POST':
            sql = 'select * from nodes join sites_node on nodes.id=sites_node.nid where sites_node.sid = %s and sites_node.status = 1' % id
            status = []
            for node in self.Site.query(sql):
                uri = 'http://%s/ocdn/purge?token=%s&domain=http%s' % (node.host,node.token,Helper.hash(node.sid))
                #1.清理节点缓存
                if Helper.get_node_api(uri) is None:
                    status.append(str(node.id)+'lost')
                else:
                    status.append(str(node.id)+'ok')
            say = ','.join(status)
            return self.render_json({'msg':'节点缓存删除成功.# %s' % say})

    #网站添加帮助
    def help(self,id):
        self._load_site(id)
        if self.site.is_cname == 0:
            if Helper.get_cname(self.site.domain):
                self.Site.update_by_cname(id)

    #删除站点
    def destory(self,id):
        self.load = False
        self._load_site(id)
        if self.Site.destory(id):
            web.seeother('/sites')

    #对应的节点站点流量
    def node_traffic(self,id,nid):
        self._load_site(id)
        self.data['tab'] = 'traffic'
        self.data['nid'] = nid
        if self.method == 'POST':
            #获取4个小时
            t   = int(int(time.time())-4*60*60)
            end = time.strftime("%Y-%m-%d %H:%M:00",time.localtime(t))
            #获取是否存在流量数据
            if self.Traffic.count_by("(sid = %s and nid=%s) and created_at > '%s'" % (id, nid, end)):
                data = {'hit_byte':[],'total_byte':[],'time':[],'status':True}
                for traffic in self.Traffic.get_many_by("(sid = %s and nid = %s) and created_at > '%s'" % (id,nid,end), 24, 'id asc'):
                    data['hit_byte'].append(traffic.hit_byte)
                    data['total_byte'].append(traffic.total_byte)
                    data['time'].append(traffic.created_at.strftime('%H:%M'))
                return self.render_json(data)
            else:
                return self.render_json({'msg':'没有该网站4个小时内的的统计数据.'})
